import { TagsOutlined } from '@ant-design/icons';
import { Bubble, ThoughtChain, XStream } from '@ant-design/x';
import { Button, Input, Splitter, message } from 'antd';
import React from 'react';

const App = () => {
    const [lines, setLines] = React.useState<Record<string, string>[]>([]);
    const [inputText, setInputText] = React.useState('');
    const [loading, setLoading] = React.useState(false);
    const content = lines.map((line) => line.data).join('');

    // 真实 SSE 连接
    async function connectSSE() {
        if (!inputText.trim()) {
            message.warning('请输入消息');
            return;
        }

        setLoading(true);
        setLines([]); // 清空历史数据

        try {
            const response = await fetch(
                `http://localhost:8101/api/memory_stream_chat_sse?message=${encodeURIComponent(inputText)}`,
                {
                    headers: {
                        Accept: 'text/event-stream',
                    },
                }
            );

            if (!response.ok || !response.body) {
                throw new Error(`SSE连接失败: ${response.status}`);
            }

            // 使用XStream处理SSE流
            for await (const chunk of XStream({ readableStream: response.body })) {
                if (chunk.data === '[DONE]') break;

                try {
                    setLines((prev) => [...prev, chunk]);
                } catch (e) {
                    console.warn('解析SSE数据失败:', e);
                }
            }
        } catch (err) {
            message.error(`SSE连接异常: ${err.message}`);
            console.error(err);
        } finally {
            setLoading(false);
        }
    }

    return (
        <Splitter>
            <Splitter.Panel>
                <div style={{ marginBottom: 16 }}>
                    <Input
                        value={inputText}
                        onChange={(e) => setInputText(e.target.value)}
                        placeholder="输入消息..."
                        style={{ marginRight: 8, width: 200 }}
                    />
                    <Button
                        type="primary"
                        onClick={connectSSE}
                        loading={loading}
                        disabled={loading}
                    >
                        发送消息
                    </Button>
                </div>

                {/* 实时内容展示 */}
                {content && <Bubble content={content} />}
            </Splitter.Panel>

            {/* 调试信息面板 */}
            <Splitter.Panel style={{ marginLeft: 16 }}>
                <ThoughtChain
                    items={
                        lines.length > 0
                            ? [
                                {
                                    title: 'SSE 流日志',
                                    status: 'success',
                                    icon: <TagsOutlined />,
                                    content: (
                                        <pre style={{ overflow: 'auto', maxHeight: 10000 }}>
                        {lines.map((line, index) => (
                            <code key={index}>{JSON.stringify(line, null, 2)}</code>
                        ))}
                      </pre>
                                    ),
                                },
                            ]
                            : []
                    }
                />
            </Splitter.Panel>
        </Splitter>
    );
};

export default App;